package router

import "C"
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

type Option func(engine *gin.Engine)

var options = []Option{}

// 注册app的路由配置
func Include(opts ...Option) {
	options = append(options, opts...)
}

var ApiWhiteList = map[string]string{
	"/api/users/login/":       "login",
	"/test":                   "test",
	"/api/plan/calender":      "calendar",
	"/api/users/wechat":       "wechat",
	"/api/users/wechat2":      "wechat",
	"/api/users/loginByAuths": "",
	"/api/bill/create":        "",
	"/api/bill/search":        "bill",
}

//siteMap = make(map[string]string)
//siteMap [ "Baidu" ] = "百度"

// 初始化
func Init() *gin.Engine {
	r := gin.Default()
	r.Use(Cors())

	//登录认证
	//loginGroup := r.Group("/api/v1/login")
	//{
	//	loginGroup.POST("/", utils.Login)          //登录服务器
	//	loginGroup.POST("/refresh", utils.Refresh) //生成新token
	//}

	//r.Use(func(c *gin.Context) {
	//	// 查看url在白名单中是否存在
	//	_, ok := ApiWhiteList[c.Request.RequestURI]
	//	if ok {
	//		return
	//	}
	//	if c.Request.RequestURI == "/api/v1/login" {
	//		return
	//	}
	//	//身份认证
	//	checkUser, _, err := utils.Verify(c) //第二个值是用户名，这里没有使用
	//	if err != nil {
	//		c.JSON(400, gin.H{"err": err.Error()})
	//		return
	//	}
	//	if checkUser == false {
	//		c.JSON(401, gin.H{"err": "身份认证失败"})
	//		return
	//	}
	//})
	for _, opt := range options {
		opt(r)
	}
	return r
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method //请求方法
		log.Println("请求方法：", method)
		origin := c.Request.Header.Get("Origin") //请求头部
		//str := fmt.Sprintf("处理请求，Origin：%v; Method：%v; Request:%v", origin, method, c.Request)
		//log.Println(str)
		var headerKeys []string
		for k, _ := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}

		if origin != "" {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", "*")             //允许访问所有域
			c.Header("Access-Control-Allow-Private-Network", "true") //chrome 92+ 新增了私有网络访问限制，需要加上这个
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token, session, X_Requested_With, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language, DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-type, Pragma")

			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Private-Network, Cache-Control, Content-Length, Content-type, Expires, Last-Modified, Pragma, FooBar")

			c.Header("Access-Control-Max-Age", "172800")             //缓存请求信息，单位为秒
			c.Header("Access-Control-Allow-Credentials", "false")    //跨域请求是否需要带cookie信息 默认这是true
			c.Set("Content-Type", "application/json; charset=UTF-8") //这是返回格式是json
		}

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSONP(http.StatusOK, "Options Request!")
		}
		//处理请求
		c.Next()
	}

}
